package com.topcheer.provider.rbac.service;

import com.topcheer.common.api.base.vo.BaseUser;
import com.topcheer.common.base.annotation.Cache;
import com.topcheer.provider.rbac.entity.Operation;
import com.topcheer.provider.rbac.entity.Role;
import com.topcheer.provider.rbac.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xutao
 * @Package com.example.baseline.rbac.service
 * @Description: ${todo}
 * @date 2020/3/31 19:48
 */
@Service
public class PermissionService {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    OperationService operationService;
    @Cache(prefix = "baseUser:",key = "#loginName")
    public BaseUser getUserInfo(String loginName){
        BaseUser result = new BaseUser();
        User user = new User();
        user.setLoginName(loginName);
        List<User> userList = userService.select(user);
        if(!CollectionUtils.isEmpty(userList)){
            User userInfo = userList.get(0);
            List<Role> roleList = roleService.selectRoleByUserId(userInfo.getId());
            List<Operation> operationList = operationService.selectOperation(userInfo.getId());
            BeanUtils.copyProperties(userInfo,result);
            List<com.topcheer.common.api.base.vo.Role> roles = roleList.stream().map(role -> {
                com.topcheer.common.api.base.vo.Role target = new com.topcheer.common.api.base.vo.Role();
                BeanUtils.copyProperties(role, target);
                return target;
            }).collect(Collectors.toList());
            List<com.topcheer.common.api.base.vo.Operation> operations = operationList.stream().map(operation -> {
                com.topcheer.common.api.base.vo.Operation target = new com.topcheer.common.api.base.vo.Operation();
                BeanUtils.copyProperties(operation, target);
                return target;
            }).collect(Collectors.toList());
            result.setOperationList(operations);
            result.setRoleList(roles);
        }
        return result;
    }
}
